#include "packet.h"

Packet::Packet(Register* reg)
: _opcode(0)
, _register(reg)
{
}

Packet::Packet(uint16 opcode, Register* reg)
: _opcode(opcode)
, _register(reg)
{
}

Packet::Packet(const Packet &r)
: ByteBuffer(r)
, _opcode(r._opcode)
, _register(r._register)
{
}

Packet& Packet::operator= (const Packet& r)
{
	if(this != &r)
	{
		ByteBuffer::operator= (r);

		_opcode = r._opcode;
		_register = r._register;
	}

	return *this;
}

bool Packet::DecodePacket(const uint8* data, const uint16 size)
{	
	Append(data, size);

	return true;
}

/////////////////////////////////////     NetPacket      ///////////////////////////////////////

NetPacket::NetPacket(Register* reg)
: Packet(reg)
{
}

NetPacket::NetPacket(uint16 opcode, Register* reg)
: Packet(opcode, reg)
{
}

NetPacket::NetPacket(const Packet &r)
: Packet(r)
{
}

NetPacket& NetPacket::operator= (const NetPacket& r)
{
	if(this != &r)
	{
		Packet::operator= (r);
	}

	return *this;
}

void NetPacket::EncodePacket()
{
	uint16 version = NET_PACKET_VERSI0N;
	uint16 len = Size() + NET_PACKET_OFFSET;

	vector<uint8> dst;
	Copy(dst);

	Clear();
	(*this)<<len<<version<<GetOpcode();
	if(!dst.empty()) Append(&dst[0], dst.size());
}

bool NetPacket::DecodePacket(const uint8* data, const uint16 size)
{
	int index = 2;

	//VERSION
	if(index + 2 > size)
	{
		ELOG("Packet failed: version size does not match\n");
		return false;
	}
	uint16 version;
	memcpy((uint8*)&version, &data[index], 2);
	version = ntohs(version);
	if(version != NET_PACKET_VERSI0N)
	{	
		ELOG("Packet failed: version error\n");
		return false;
	}

	//OPCODE
	index += 2;
	if(index + 2 > size)
	{
		ELOG("Packet failed: opcode size does not match\n");
		return false;
	}
	uint16 opcode = 0;
	memcpy((uint8*)&opcode, &data[index], 2);
	opcode = ntohs(opcode);
	SetOpcode(opcode);

	//DATA
	index += 2;
	if(index < size)
	{
		Append(&data[index], size - index);
	}
	
	return true;
}